/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.pc.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author Yuriy Dunko
 */
public class ArraySet <E extends Comparable<E>> // extends ArrayList<E>
        implements Set<E>{
    private TreeSet<E> set = new TreeSet<E>();
    private ArrayList<E> list = new ArrayList<E>();

    public ArraySet() {
    }

    public ArraySet(E... c) {
        this(Arrays.asList(c));
    }

    public ArraySet(Collection<? extends E> c) {
        addAll(c);
    }

    @Override
    public boolean add(E e) {
        if (set.contains(e)){
            return false;
        }
        set.add(e);
        return list.add(e);
    }

    @Override
    public boolean remove(Object o) {
        set.remove((E)o);
        return list.remove((E)o);
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        boolean added = false;
        for (E e : c) {
            if (set.add(e)){
                added = true;
                list.add(e);
            }
        }
        return added;
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        set.retainAll(c);
        return list.retainAll(c);
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        set.removeAll(c);
        return list.removeAll(c);
    }

    @Override
    public void clear() {
        set.clear();
        list.clear();
    }

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
        return set.contains((E)o);
    }

    @Override
    public Iterator<E> iterator() {
        return list.iterator();
    }

    @Override
    public Object[] toArray() {
        return list.toArray();
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return list.toArray(a);
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return set.containsAll(c);
    }

    @Override
    public boolean equals(Object obj) {
        return set.equals(obj);
    }

}
